import requests
import re
from lxml import etree
from fontTools.ttLib import TTFont


class SendRequest:
    def __init__(self):
        self.url = 'https://www.qidian.com/rank/yuepiao/'
        self.headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36',
            'referer': ''
        }
        self.session = requests.session()

    def URequest(self):
        response = self.session.get(self.url, headers=self.headers)
        return response


class QiDian(SendRequest):
    def getIndex(self):
        response = self.URequest()
        text_html = response.content.decode()
        with open('qidian.html', 'w', encoding='utf-8')as f:
            f.write(text_html)
        woff_url = re.findall("format\('eot'\); src: url\('(.*?)'\) format\('woff'\)", text_html)[0]
        self.url = woff_url
        novel_titles = etree.HTML(text_html).xpath('//*[@id="book-img-text"]/ul/li/div[2]/h2/a/text()')
        print(novel_titles)
        tickets = re.findall('</style><span class="\w+">(.*?);</span></span>月票</p>', text_html)
        print(tickets)
        woff_res = self.URequest()
        with open('qidian.woff', 'wb')as f:
            f.write(woff_res.content)
        font_file = TTFont('qidian.woff')
        font_file.saveXML('qidian.xml')
        best_map = font_file.getBestCmap()
        return novel_titles, tickets, best_map

    def dealFont(self):
        novel_titles, tickets, best_map = self.getIndex()
        zh_en = {
            'zero': 0, 'one': 1, 'two': 2, 'three': 3,
            'four': 4, 'five': 5, 'six': 6, 'seven': 7,
            'eight': 8, 'nine': 9
        }
        result = {} # 用于存放最终的数据，键为书名，值为月票
        for i, j in zip(novel_titles, tickets):
            t_num = j.replace('&#', '').split(';')  # 消除&#后以分号进行分割
            print(t_num)
            res_ticket = '' # 用于记录每一本书字体解密之后的内容
            for l in t_num:
                res_ticket += str(zh_en[best_map[int(l)]])  # 根据网站中提取出来的加密数据映射字体文件中
                # 的目标值，然后由于目标值是英文所以需要映射成阿拉伯数字，最后进行连接称为该本书最终的月票信息
            result[i] = res_ticket
        print(result)


if __name__ == '__main__':
    q = QiDian()
    q.dealFont()